package main

import (
	"os"
	"os/exec"
	"path/filepath"
	"strings"
	"unicode/utf8"

	log "github.com/alecthomas/log4go"
	sego "github.com/huichen/sego"
)

type HupuSego struct {
	segmenter *sego.Segmenter
}

var gHupuSego *HupuSego

func InitHupuSego() {
	gHupuSego = NewHupuSego()
}

func NewHupuSego() *HupuSego {
	file, _ := exec.LookPath(os.Args[0])
	path, _ := filepath.Abs(file)
	dir := filepath.Dir(path)
	dictPath := filepath.Join(dir, "dictionary_hupu.txt")

	adaptor := &HupuSego{}

	adaptor.segmenter = &sego.Segmenter{}
	adaptor.segmenter.LoadDictionary(dictPath)
	return adaptor
}

func (self *HupuSego) getNames(text string) map[string]int {
	segments := self.segmenter.Segment([]byte(text))
	result := make(map[string]int)
	nameCache := ""
	for _, seg := range segments {
		if seg.Token().Pos() == "nrf" {
			if len(nameCache) == 0 || strings.HasSuffix(nameCache, "-") || strings.HasSuffix(seg.Token().Text(), "-") {
				nameCache += seg.Token().Text()
			} else {
				nameCache = strings.Trim(nameCache, "-")
				result[nameCache] = result[nameCache] + 1
				nameCache = ""
			}
		} else if seg.Token().Pos() == "nrc" {
			nameCache = seg.Token().Text()
			result[nameCache] = result[nameCache] + 1
		} else if strings.HasPrefix(seg.Token().Pos(), "nr") {
			nameCache += seg.Token().Text()
		} else if seg.Token().Text() == "-" && len(nameCache) > 0 {
			nameCache += "-"
		} else {
			if utf8.RuneCountInString(nameCache) > 1 {
				nameCache = strings.Trim(nameCache, "-")
				result[nameCache] = result[nameCache] + 1
			}
			nameCache = ""
		}
	}

	log.Trace(sego.SegmentsToString(segments, false))

	return result
}
